var shareInfo = {
    title : $("#share_content .share_title").text(),
    url : self.location.origin+self.location.pathname,
    desc : $("#share_content .share_desc").text(),
    imgurl : $("#share_content .share_pic").data("src")
};

var info = {
    title : [
        "靠颜值成为了网易游戏代言人！",
        "靠智商成为了网易游戏代言人！",
        "靠霸气成为了网易游戏代言人！",
        "靠财富成为了网易游戏代言人！",
        "靠专一成为了网易游戏代言人！",
        "靠专一成为了网易游戏代言人！"
    ],
    text : [
        "靠颜值成为了网易游戏ChinaJoy红色主场代言人！如此突破天际的爆表颜值连芙蓉姐姐都要自愧不如！",
        "靠智商成为了网易游戏ChinaJoy红色主场代言人！大脑如此发达，简直是万中无一的超智慧生物！哈服，耶撸，麻神大学抢着要你呢吧！",
        "靠霸气成为了网易游戏ChinaJoy红色主场代言人！废话不多说，不点赞的赏个一丈红，不转发的滚去宗人府！",
        "靠财富成为了网易游戏ChinaJoy红色主场代言人！富可敌国算什么？此人连宠物狗都有试衣间。",
        "靠专一成为了网易游戏ChinaJoy红色主场代言人！面对思葱的追求，此人毫不动摇，与脑残志坚的爱人不离不弃誓要相守白头。",
        "靠专一成为了网易游戏ChinaJoy红色主场代言人！面对思葱的追求，此人毫不动摇，与脑残志坚的爱人不离不弃誓要相守白头。"
    ]
}

info['index'] = Math.floor((Math.random()*info.title.length));

var NIE_weixin = {
    user : {}
};

var GET = (function (){
    var url = self.location.href.toString();
    var u = url.split("?");
    if(typeof(u[1]) == "string"){
        u = u[1].split("&");
        var get = {};
        for(var i in u){
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();

var _animates;
var isReady = false;
MobileTopic.createTopic({
	warper:"#specile",
	containerDiv:"#stage",
	stages:".stage",
	duration:800,
	activeClassName:"inited",
	isAutoToNextStage:false,
	isReplay:true,
	isHorizontal:false,
	stageBgs:[],
	swipeCallback:function(param){
	},
	initedCallback:function(){
		_animates = MobileTopic.getAinmateEles();
	}
});

MobileTopic.init();


function eraserStage(_num){

    typeof _num == "undefined" && (_num = 0);

    var fillArr = [true, false, false, false, false, false];
    var that = this;

    if(!fillArr[_num]){
        return true;
    }

    $(".shade-cav").show(0, function(){
        $(".shade-cav .cav-show").hide().eq(_num).show().eraser({
            completeRatio: .1,
            completeFunction: function (){
                if (fillArr[_num]) {
                    this.canvas.parent().fadeOut('3000', function() {
                        $("#stage4").addClass('inited');
                    });
                }
            }
            // autoSwipe : {
            //     fill : fillArr[_num],
            //     cbk  : function(canvas) {
            //         if (!fillArr[_num]) {
            //             canvas.parent().fadeOut('3000', function() {
            //                 $("#stage4").addClass('inited');
            //             });
            //         }
            //     }
            // }
        });
    });
}

function shakeStage(_i){

    typeof _i == "undefined" && (_i = 0);

    if($("#stage2 .st2-icon").eq(_i).data("shake") == true) {
        return false;
    }

    $("#stage2 .st2-icon").eq(_i).addClass('shake-icon').data("shake" , true);
    setTimeout(function (){
        $("#stage2 .st2-icon").eq(_i).removeClass('shake-icon');
    }, 3*1000);
    (function (){
        var setInt = [];
        setInt[_i] = [];
        $("#stage2 .st2-icon").eq(_i).find(".icon").each(function (){
            if($(this).find('i').length != 0 && Number($(this).data("i")) > 0){
                var num = Number($(this).data("i"));
                var i = 0;
                var index = $(this).index();
                var _slef = this;
                $(this).find('i').text(1);

                setInt[_i][ index ] = setInterval(function (){
                    i++;
                    $(_slef).find('i').text(i);
                    if(i >= num){
                        clearInterval(setInt[_i][ index ]);
                    }
                }, (3000/num));
            }
        });
    })();
}

(function ($){


    $.getScript("http://sc.tool.netease.com/sharecom/wxjs.php?url="+encodeURIComponent(self.location.href)+"&_="+new Date().getTime(), function (){

        wx.config({
            debug: false,
            appId: wx_conf.appId,
            timestamp: wx_conf.timestamp,
            nonceStr: wx_conf.nonceStr,
            signature: wx_conf.signature,
            jsApiList: [
                'chooseImage',
                'uploadImage',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo'
            ]
        });

        loadAll();

        wx.ready(function () {
            isReady = true;
        });
        wx.error(function(res){});
    });

    var num = 0;
    MobileTopic.scorllTo = function (_num){
        num = _num;
        var _height = $("#specile").innerHeight();
        $("#stage").css("-webkit-transform", "translate(0px, -"+(_num*_height)+"px)");
    };

    function loadAll(){


        function getWinxinInfo(){

            if(typeof GET['code'] != "undefined" && GET['code'] != ""){

                $.getJSON('http://106.2.34.245/php/nie_wx/api.php?callback=?',
                {
                    need_userinfo: 1,
                    code : GET['code']
                }, function(_d) {

                    if(_d.success == false){

                        alert(_d.msg);

                        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx85f583832dbd07e9&redirect_uri="+encodeURIComponent(self.location.origin+self.location.pathname)+"&response_type=code&scope=snsapi_userinfo#wechat_redirect";

                        return false;
                    }else{

                        NIE_weixin.user['nickname'] = _d.nickname;
                        NIE_weixin.user['id'] = _d.user_bid;

                        shareInfo['title'] = NIE_weixin.user['nickname']+info['title'][ info['index'] ];
                        shareInfo['desc'] = NIE_weixin.user['nickname']+info['title'][ info['index'] ];

                        showNews({
                            nickname : _d.nickname,
                            _index : info['index']
                        });

                        wx.ready(function() {

                            wx.onMenuShareAppMessage({
                                title   : '2015ChinaJoy重大头条',
                                desc    : shareInfo.desc,
                                link    : shareInfo.url,
                                imgUrl  : shareInfo.imgurl,
                                success : function() {
                                }
                            });

                            wx.onMenuShareTimeline({
                                title   : shareInfo.desc,
                                // desc    : shareInfo.desc,
                                link    : shareInfo.url,
                                imgUrl  : shareInfo.imgurl,
                                success : function() {
                                }
                            });
                        });

                        musicPlay();

                    }

                });

            }else{

                window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx85f583832dbd07e9&redirect_uri="+encodeURIComponent(self.location.origin+self.location.pathname)+"&response_type=code&scope=snsapi_userinfo#wechat_redirect";

                return false;

            }

        }

        function showNews(_con){

            $("#stage12 .content>h2").text( decodeURIComponent(_con['nickname'])+info['title'][ _con['_index'] ] );
            $("#stage12 .content>p").text( decodeURIComponent(_con['nickname'])+( info['text'][ _con['_index'] ].replace(/xxx/ig, decodeURIComponent(_con['nickname'])) ) );

        }


        var shareToWeiXin = function(){
            //分享到微信



            // var onBridgeReady = function() {
            //     var appId = '';
            //     WeixinJSBridge.on('menu:share:appmessage', function(argv) {
            //         WeixinJSBridge.invoke('sendAppMessage', {
            //             'img_url': shareInfo.imgurl,
            //             'img_width': '640',
            //             'img_height': '640',
            //             'link': shareInfo.url,
            //             'desc': shareInfo.desc,
            //             'title': '2015ChinaJoy重大头条'
            //         }, function(res) {
            //         });
            //     });

            //     WeixinJSBridge.on('menu:share:timeline', function(argv) {
            //         WeixinJSBridge.invoke('shareTimeline', {
            //             'img_url': shareInfo.imgurl,
            //             'img_width': '640',
            //             'img_height': '640',
            //             'link': shareInfo.url,
            //             'desc': shareInfo.desc,
            //             'title': shareInfo.desc
            //         }, function(res) {
            //         });
            //     });
            // };
            // if (document.addEventListener) {
            //     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            // } else if (document.attachEvent) {
            //     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            //     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            // };
        };

        // var shareToYiXin = function(){
        //     //分享到易信
        //     var onBridgeReady = function(){
        //         YixinJSBridge.on('menu:share:appmessage', function(argv) {
        //             YixinJSBridge.invoke('sendAppMessage', {
        //                 'img_url': shareInfo.imgurl,
        //                 'img_width': '640',
        //                 'img_height': '640',
        //                 'link': shareInfo.url,
        //                 'desc': shareInfo.desc,
        //                 'title': '2015ChinaJoy重大头条'
        //             }, function(res) {
        //             });
        //         });
        //         YixinJSBridge.on('menu:share:timeline', function(argv) {
        //             YixinJSBridge.invoke('shareTimeline', {
        //                 'img_url': shareInfo.imgurl,
        //                 'img_width': '640',
        //                 'img_height': '640',
        //                 'link': shareInfo.url,
        //                 'desc': shareInfo.desc,
        //                 'title': shareInfo.desc
        //             }, function(res) {
        //             });
        //         });
        //     };

        //     if (document.addEventListener) {
        //         document.addEventListener('YixinJSBridgeReady', onBridgeReady, false);
        //     } else if (document.attachEvent) {
        //         document.attachEvent('YixinJSBridgeReady', onBridgeReady);
        //         document.attachEvent('onYixinJSBridgeReady', onBridgeReady);
        //     };
        // };

        // shareToWeiXin();
        // shareToYiXin();

        (function (){

            var hastouch = null;

            touch.on("#stage1 .touch", "touchstart", function (ev){
                ev.preventDefault();

                if($("#stage1 .touch").data("touch") == true){
                    return false;
                }

                $("#stage1 .touch").data("touch", true);

                $("#stage1 .touch").addClass('handrun');
                $("#stage1 .touch .hand .hand-2").stop().animate({
                    height: "100%"
                }, 1*1000, function() {

                    // 指纹开启成功后回调
                    $("#stage1 .touch .hand").data("touch", true);
                    $("#stage1 .touch .hand .hand-1").hide();
                    $(".hand-bg").addClass('hand-bg-big');

                    setTimeout(function(){
                        $(".hand-bg").removeClass('hand-bg-big');
                        $(".stage-shade").show(0, function (){
                            MobileTopic.scorllTo(1);
                        });
                        setTimeout(function (){
                            $(".stage-shade").addClass('stage-shade-hide');
                            setTimeout(function (){
                                $(".tipsshare").css("display","block");
                                shakeStage();
                                $(".stage-shade").hide(0, function (){
                                    $(".stage-shade").removeClass('stage-shade-hide');
                                });
                                setTimeout(function (){
                                    $(".tipsshare .pop-bg").css("display","block");
                                    $(".tipsshare").addClass('tipsisClick');
                                    hastouch = setTimeout(function (){
                                        $(".tipsshare").addClass("anishow");
                                        setTimeout(function (){
                                            $(".tipsshare").css("display","none").removeClass("anishow");
                                        }, 2000);
                                    }, 100);
                                }, 100);
                            }, 700);
                        }, 800);
                    }, 620);

                });
            });


            var anw = false;

            var canvsss = false;

            window.shadeCnv = function (){

                if(canvsss){
                    return true;
                }
                canvsss = true;

                $(".con-bg").addClass('con-bg-big');
                setTimeout(function(){
                    $(".con-bg").removeClass('con-bg-big');
                    $(".stage-shade").show();
                    MobileTopic.scorllTo(3);
                    setTimeout(function (){
                        eraserStage();
                        $(".stage-shade").addClass('stage-shade-hide');
                        setTimeout(function (){
                            $(".stage-shade").hide(0, function (){
                                $(".stage-shade").removeClass('stage-shade-hide');
                            });
                        }, 300);
                    }, 800);
                }, 600);
            }

            //第二页 icon 动画
            $("#stage2 .st2-icon .icon").click(function (e){
                e.preventDefault();

                var _self = this;

                // 第一次点击，抖动+弹层
                // if(!anw){
                //     anw = true;
                //     $(this).addClass('icon-shake-img');
                //     setTimeout(function (){
                //         $(_self).removeClass('icon-shake-img');
                //         $(".tipsshare2").show(0, function (){
                //             $(".tipsshare2").addClass('anishow');
                //             setTimeout(function (){
                //                 $(".tipsshare2").removeClass('anishow').css('display', 'none');
                //             }, 4000);
                //         });
                //     }, 1*1000);
                //     return false;
                // }

                // 第二次点击
                $(this).addClass('icon-shake-img');
                setTimeout(function (){

                    $(_self).removeClass('icon-shake-img');
                    $(_self).addClass('icon-big');

                    setTimeout(function(){
                        $(_self).removeClass('icon-big');
                        $(".stage-shade").show();
                        MobileTopic.scorllTo(2);
                        setTimeout(function (){
                            $(".stage-shade").addClass('stage-shade-hide');
                            setTimeout(function (){
                                $(".stage-shade").hide(0, function (){
                                    $(".stage-shade").removeClass('stage-shade-hide');
                                    stage3moving();
                                });
                                // stage3moving();
                            }, 300);
                        }, 800);
                    }, 620);
                }, 1*1000);

            });

            // 第二页手指拖动
            touch.on("#stage2", "swiping", function (e){

                var num = (e.distanceX / $("#stage2").innerWidth() )*100;

                if($("#stage2 .pageall").data("page") == 1 && e.distanceX < 0){

                    $("#stage2 .pageall").stop().css("left", num+"%");

                }else if($("#stage2 .pageall").data("page") == 2 && e.distanceX > 0){

                    $("#stage2 .pageall").stop().css("left", (num-100)+"%");

                }
            });

            touch.on("#stage2", "swipeend", function (e){

                var num = (e.distanceX / $("#stage2").innerWidth() )*100;

                if($("#stage2 .pageall").data("page") == 1 && e.distanceX < 0){

                    if(num < -50){
                        $("#stage2 .pageall").data("page", 2);
                        shakeStage(1);
                        $("#stage2 .pageall").stop().animate({
                            left: "-100%"
                        }, 200);
                    }else{
                        $("#stage2 .pageall").stop().animate({
                            left: "0%"
                        }, 200);
                    }

                }else if($("#stage2 .pageall").data("page") == 2 && e.distanceX > 0){

                    if(num > 50){
                        $("#stage2 .pageall").data("page", 1);
                        shakeStage(0);
                        $("#stage2 .pageall").stop().animate({
                            left: "0%"
                        }, 200);
                    }else{
                        $("#stage2 .pageall").stop().animate({
                            left: "-100%"
                        }, 200);
                    }

                }
            });

            touch.on(".tipsshare2", "tap", function (){
                $(".tipsshare2").hide();

            });

            $("#stage4").data("haibao", 0);


            var isBusyDown = false;

            window.haibaoMove = function(){

                if (isBusyDown) {
                    return;
                }

                isBusyDown = true;

                if($(this).parents(".haibao").is("#stage9")){

                    MobileTopic.scorllTo(9);
                    $("#stage10 .content1").addClass('aniShowtxt2');
                    setTimeout(function(){
                        $(".con-bg").removeClass('con-bg-big');
                        $("#stage3").addClass('inited');
                        setTimeout(function(){
                            MobileTopic.scorllTo(10);
                            $("#stage11").addClass('inited');
                            stage11moving();
                        },6*1000);
                    },630);

                    return false;
                }

                var  num = Number($("#stage4").data("haibao"));

                num += 1;
                $("#stage4").data("haibao", num);
                $(".haibao").removeClass('inited');
                $("#stage"+(num+4)).addClass('inited');

                MobileTopic.scorllTo(3+num);

                setTimeout(function() {
                    isBusyDown = false;
                }, 800);
            }

            var isMoving = false;

            window.haibaoMovePrev = function(){

                if (isMoving) {
                    return;
                }

                isMoving = true;

                var  num = Number($("#stage4").data("haibao"));

                if (num <= 0) {
                    return;
                }

                num -= 1;
                $("#stage4").data("haibao", num);
                $(".haibao").removeClass('inited');
                $("#stage"+(num+4)).addClass('inited');

                MobileTopic.scorllTo(3+num);

                setTimeout(function() {
                    isMoving = false;
                }, 800);
            }

            // 海报切换
            touch.on(".haibao", "swipeup", function (e){
                haibaoMove.call(this);
            });
            touch.on(".haibao", "swipedown", function (e){
                haibaoMovePrev.call(this);
            });

            touch.on("#stage12 .content", "swiping", function (e){
                $("#stage12 .content").scrollTop(-e.distanceY);
            });

            // 播放完文字后调用监听
            window.moveSage4 = function (){
                touch.on("#stage3", "swipeup", function (){
                    shadeCnv();
                });
            }

            // 第三屏动画
            window.stage3moving = function(){
                $("#stage3 .content1").addClass('aniShowtxt');
                setTimeout(function(){
                    $(".con-bg").removeClass('con-bg-big');
                    $("#stage3").addClass('inited');
                    setTimeout(function(){
                        moveSage4();
                    }, 300);
                }, 300);
            };

            // 如果是被分享出去的，先展示新闻页
            if( typeof GET['pic'] != "undefined" && GET['pic'] != "" && typeof GET['username'] != "undefined"){

                showNews({
                    nickname : GET['username'],
                    _index : GET['index']
                });

                $("#stage12 .showImg1 .showImg1-box, #stage12 .showImg2 .showImg2-box").css("background-image", "url('http://106.2.34.245/php/nie_pic/upload/"+encodeURIComponent(GET['pic'])+"/my.jpg')");

                $(".stage-shade").removeClass('stage-shade-hide').show(0, function (){
                    MobileTopic.scorllTo(11);

                    setTimeout(function (){
                        $(".stage-shade").hide(1000);
                        $("#topmost_cover").fadeOut(1000);
                    }, 2000);
                });

                $("#stage12 .close").show();
                $("#stage12").addClass('share-in');
                $("#stage12 .come-in").show();
                $("#stage12 .share").hide();
                setTimeout(function (){
                    $(".stage-shade").addClass('stage-shade-hide');
                    setTimeout(function (){
                        $(".stage-shade").hide(0, function (){
                            $(".stage-shade").removeClass('stage-shade-hide');
                            $("#stage12").addClass('inited');
                        });
                    }, 300);
                }, 800);

            }else{
                $("#topmost_cover").fadeOut(1000);


                // !!!!
                // GET WEIXIN
                getWinxinInfo();

            }

            $("#stage12 .close, #stage12 .come-in").click(function() {

                getWinxinInfo();
                return false;

            });

            function previewPic(_id, _do){
                $.getJSON('http://106.2.34.245/php/nie_pic/api.php?callback=?',
                    {
                        sid : _id
                    }, function(_d) {
                        if(_d.status == "ok"){
                            if(_do == "my"){
                                NIE_weixin.pic_url = _d.myid;
                            }
                            $("#stage12 .showImg1 .showImg1-box, #stage12 .showImg2 .showImg2-box").css("background-image", "url('http://106.2.34.245/php/nie_pic/upload/"+_d.myid+"/my.jpg')");
                            stage12moving();
                        }
                });
            }

            window.stage11moving = function(){
                $("#stage11 .push, #stage11 .con-box img").unbind('click').click(function(event) {
                    wx.chooseImage({
                        count: 1,
                        success: function (res) {
                            var localIds = res.localIds;
                            if(localIds.length == 0) {
                                alert('请选择图片！');
                                return;
                            }
                            var img = localIds[0];
                            wx.uploadImage({
                                localId: img,
                                isShowProgressTips: 1,
                                success: function (res) {
                                    MobileTopic.scorllTo(11);
                                    $("#stage12").addClass('inited');
                                    previewPic(res.serverId, "my");
                                }
                            });
                        }
                    });
                });
            }

            window.stage12moving = function(){

                shareInfo.url = self.location.origin+self.location.pathname+"?pic="+encodeURIComponent(NIE_weixin.pic_url)+"&index="+info['index']+"&username="+encodeURIComponent(NIE_weixin.user['nickname']);

                $(".share").click(function() {
                    /* Act on the event */
                    // $("#stage .con-box").addClass("showBig");
                    // setTimeout(function(){
                    //     $("#stage .con-box").removeClass("showBig");
                    // },2000);

                    wx.onMenuShareAppMessage({
		                title   : '2015ChinaJoy重大头条',
		                desc    : shareInfo.desc,
		                link    : shareInfo.url,
		                imgUrl  : shareInfo.imgurl,
		                success : function() {
		                }
		            });

		            wx.onMenuShareTimeline({
		                title   : shareInfo.desc,
		                // desc    : shareInfo.desc,
		                link    : shareInfo.url,
		                imgUrl  : shareInfo.imgurl,
		                success : function() {
		                }
		            });


                    $(".popshare").show();
                    $(".popshare").click(function(event) {
                        $(".popshare").hide();
                    });
                });
            }

        })();

        // 音频播放
        window.musicPlay = function(){
            var Pmusic = document.getElementById("music");

            Pmusic.play();

            $(".music-btn").click(function(e){
                e.stopPropagation();
                if($(this).hasClass("closem")){
                    $(this).removeClass("closem");
                    Pmusic.play();
                }else{
                    $(this).addClass("closem");
                    Pmusic.pause();
                }
                return false;
            });
            Pmusic.addEventListener('ended', function(){
                $(".music-btn").addClass('closem');
            }, false);

            $('body').one('touchstart', function() {
                if (!$(".music-btn").hasClass("closem")) {
                    Pmusic.play();
                }
                return false;
            });
        }

        function moveIcon(){
            var l = Math.ceil($(".page1 .st2-icon .icon").length / 4);
            var ll = $(".page1 .st2-icon .icon").outerHeight(true) * l;
            if(ll > $(".pageall").innerHeight()){
                $(".page1 .st2-icon .icon:last").detach().appendTo('.page2 .st2-icon');
                moveIcon();
            }
            return false;
        }
        moveIcon();

        $(".stage .arrow-main").click(function() {
            if($(this).parents(".stage").is("#stage3")){
                shadeCnv();
                return false;
            }

            if($(this).parents(".stage").hasClass("haibao")){
                haibaoMove.call(this);
                return false;
            }

            MobileTopic.scorllTo(num+1);
        });

    };


})(jQuery);